/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.testimonials;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.TestimonialModuleConstants;
import com.blandware.atleap.common.parsers.html.HTMLPlainTextExtractor;
import com.blandware.atleap.common.util.ConvertUtil;
import com.blandware.atleap.model.testimonials.Testimonial;
import com.blandware.atleap.search.SearchManager;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.service.testimonials.TestimonialManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.testimonials.TestimonialForm;
import com.blandware.atleap.webapp.util.core.LocaleUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.blandware.atleap.webapp.util.testimonials.TestimonialModuleWebConstants;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>Creates new testimonial
 * </p>
 * <p><a href="CreateTestimonialAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @version $Revision: 1.18 $ $Date: 2008/04/29 17:52:51 $
 * @struts.action path="/testimonials/create"
 * name="testimonialForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="testimonials-item-create"
 * @struts.action-forward name="inputForward"
 * path=".testimonials.createTestimonial"
 * @struts.action-forward name="listTestimonials"
 * path="/testimonials/list.do"
 * redirect="true"
 * @struts.action-forward name="callCreateTestimonial"
 * path=".testimonials.createTestimonial"
 */
public final class CreateTestimonialAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        TestimonialForm testimonialForm = (TestimonialForm) form;
        String localesMode = testimonialForm.getLocalesMode();

		if ( isBackPressed(request) ) {
            // First check, may be session has been invalidated and we need to
            // fill content locales again
            if (request.getSession().getAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY) == null) {
                List contentLocales = LocaleUtil.getInstance(servlet.getServletContext()).getEnabledLocales();
                request.getSession().setAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY, contentLocales);
            }

            // check 'check all' ckeckbox if needed
            testimonialForm.setAllCheckedFlagForBodyCheckboxes(request, localesMode);

			return mapping.findForward("inputForward");
		}

		if ( isCancelled(request) ) {
			return mapping.findForward("listTestimonials");
		}

		if ( request.getSession().getAttribute(TestimonialModuleWebConstants.TESTIMONIAL_SUBMITTED_ACTION_KEY) != null ) {
			return mapping.findForward("listTestimonials");
		}
		request.getSession().setAttribute(TestimonialModuleWebConstants.TESTIMONIAL_SUBMITTED_ACTION_KEY, "create");

		Testimonial testimonial = new Testimonial();
		WebappUtil.copyProperties(testimonial, testimonialForm, request);
		testimonial.setActive(Boolean.TRUE);

        Map bodyMap = testimonialForm.getBodyMap();
        Map bodyCheckedBoxes = testimonialForm.getBodyCheckedBoxes();
        for (Iterator i = bodyMap.entrySet().iterator(); i.hasNext();) {
            Map.Entry entry = (Map.Entry) i.next();
            String localeIdentifier = (String) entry.getKey();
            if (bodyCheckedBoxes.get(localeIdentifier) == null) {
                // if this locale is not checked, remove body
                bodyMap.put(localeIdentifier, "");
            }
        }

        WebappUtil.fillFieldValueWithDefaultLocaleValue(testimonialForm.getTitleMap(), testimonial.getTitle(), servlet.getServletContext());
        testimonial.setTitle(testimonialForm.getTitleMap());
        WebappUtil.copyFieldValue(testimonial.getBody(), bodyMap);
		TestimonialManager testimonialManager = (TestimonialManager) getBean(TestimonialModuleConstants.TESTIMONIAL_MANAGER_BEAN);

		// get all refs
		HTMLPlainTextExtractor extractor = new HTMLPlainTextExtractor();
		Set refs = new HashSet();
		for ( Iterator i = bodyMap.entrySet().iterator(); i.hasNext(); ) {
			Map.Entry entry = (Map.Entry) i.next();
			String body = (String) entry.getValue();
            if (body != null) {
                InputStream bodyIS = new ByteArrayInputStream(ConvertUtil.convertToByteArray(body));
                refs.addAll(extractor.extractAllRefs(bodyIS, Constants.DEFAULT_ENCODING));
            }
        }

		Map linkedObjects = WebappUtil.mapObjectsToRefs(refs, request.getSession().getServletContext(), request.getContextPath());

		Long testimonialId;
		String uri = null;

		try {
			// we need an ID to create URI of testimonial, so we must first create testimonial, then set URI and update testimonial
			testimonialId = testimonialManager.createTestimonial(testimonial, linkedObjects);

			uri = TestimonialModuleWebConstants.TESTIMONIAL_URI_PREFIX + "/item" + testimonialId;
			testimonial.setUri(uri);
			testimonialManager.updateTestimonial(testimonial, linkedObjects);

			if ( testimonial.getActive().booleanValue() ) {
				// index testimonial item
				SearchManager searchManager = SearchManager.getInstance(request.getSession().getServletContext());
				searchManager.reIndexPage(testimonial, request);
			}

		} catch ( BeanAlreadyExistsException e ) {
			// testimonial already exists

            // check 'check all' ckeckbox if needed
            testimonialForm.setAllCheckedFlagForBodyCheckboxes(request, localesMode);

			ActionMessages errors = new ActionMessages();
			errors.add("testimonialAlreadyExists", new ActionMessage("testimonials.errors.alreadyExists", uri));
			saveErrors(request, errors);
			saveToken(request);
			return mapping.getInputForward();
		}
		return mapping.findForward("listTestimonials");
	}
}